/*
 * @Author      : ZhouQiJun
 * @Date        : 2025-08-15 00:22:56
 * @LastEditors : ZhouQiJun
 * @LastEditTime: 2025-08-15 01:35:02
 * @Description : 设置遮罩
 */
import { getGis } from '@ol/api'
import { type GisKey, KEY } from '@ol/define'
import type { MaskOptions } from '@ol/types'
import { isGeoJson, isWKT } from '@ol/utils'
import { isNil } from 'es-toolkit'
import type { Feature } from 'ol'
// @ts-ignore
import OlExtMask from 'ol-ext/filter/Mask'

import { GeoJSON, WKT } from 'ol/format'
import type { SimpleGeometry } from 'ol/geom'

/**
 * 设置遮罩
 * @param {string} wktOrGeojson 用于生成多边形要素
 * @param {Partial} options
 * @param {GisKey} key GisKey 默认 KEY
 * @Author ZhouQiJun
 */
export default function setupMask(wktOrGeojson: string, options: Partial<MaskOptions>, key: GisKey = KEY) {
  const _options = options // merge(options, defaultMaskOptions)
  const gis = getGis(key)
  if (!gis) return null
  const map = gis.map
  let feat: Feature<SimpleGeometry> | null = null

  const dataProjection = _options.dataProjection || 'EPSG:4326'
  const featureProjection = _options.featureProjection || gis.projection

  if (isWKT(wktOrGeojson)) {
    feat = new WKT().readFeature(wktOrGeojson, {
      dataProjection,
      featureProjection,
    }) as Feature<SimpleGeometry>
  }
  if (isGeoJson(wktOrGeojson)) {
    feat = new GeoJSON().readFeature(wktOrGeojson, {
      dataProjection,
      featureProjection,
    }) as Feature<SimpleGeometry>
  }

  if (feat === null) return null
  if (isNil(map)) return null

  const mask = new OlExtMask({
    feature: feat,
    ...options,
  })
  const layers = map?.getAllLayers().filter((l) => l.get('basemap') === true)

  layers?.forEach((l) => {
    // @ts-ignore
    l.addFilter(mask)
  })
  if (_options.fitMask !== false) {
    const geo = feat.getGeometry()
    map?.getView().fit(geo!)
  }
  return feat
}
